package com.sharemarking.application.common.service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.sharemarking.application.common.entity.Menu;
import com.sharemarking.application.common.entity.Permission;
import com.sharemarking.application.common.repository.PermissionRepo;

@Service
public class PermissionService implements PermissionEvaluator {
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private PermissionRepo permissionRepo;
	@Autowired
	private HttpServletRequest request;
	
	private final GrantedAuthority adminAuthority=new SimpleGrantedAuthority("ROLE_ADMINISTRATOR");
	/**
	 * 菜单功能权限检测
	 */
	@Override
	public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
		if(authentication.getAuthorities().contains(adminAuthority)){
			request.setAttribute("permission", Integer.MAX_VALUE);
			return true;
		}
		Iterable<Menu> menus=menuService.findAllMenus();
		if(!(permission instanceof Integer))return false;
		Menu target=null;
		for(Menu menu:menus){
			if(menu.getSymbol().equals(targetDomainObject))target=menu;
		}
		if(target==null)return false;
		Integer targetPermission=target.getPermission();
		Integer p=(Integer)permission;
		Integer finalPermission=(~targetPermission)&15;
		List<String>roles=authentication.getAuthorities().stream().map(a->a.getAuthority().substring(5)).collect(Collectors.toList());
		List<Permission> permissionList=permissionRepo.findAllByMenuIdAndRoleEnameIn(target.getId(),roles);
		for(Permission rolepermission:permissionList)finalPermission|=rolepermission.getPermission();
		request.setAttribute("permission", finalPermission);
		return (finalPermission&p) > 0;
	}
	/**
	 * 未实现
	 */
	@Override
	public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
			Object permission) {
		// TODO Auto-generated method stub
		return false;
	}

}
